import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { add } from "../store/reducers/userReducer";
import { Form, Input, Button, Checkbox, message } from "antd";
import  {withRouter} from  "react-router-dom"
import useraxios from "../model/useraxios";

const Demo = (props:any) => {
  
  const success = () => {
    message.success('登录成功');
  };
  const error = () => {
    message.error('登录失败，请检查账号和密码');
  };
  const onFinish =async (values: any) => {
    let { account, password } = values;
    account = Number(account);
    // console.log(account, password);
    let {data}=await useraxios.query({account,pwd:password});
    if(data.length){
      add({account:data.account,userpwd:data.pwd,id:data.id});
      success();
      props.history.push('/home')
    }else{
      error();
    }
    
    
    
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className="login" style={{ width: 500 ,marginTop:180,marginLeft:240}}>
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="账号"
          name="account"
          rules={[
            {
              required: true,
              message: "Please input your account!",
            },
            {
              pattern: /^[0-9]{5,6}$/,
              message: "账号必须是5-6位数字",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: "Please input your password!",
            },
            {
              pattern: /^[a-z0-9_$]{6,12}$/i,
              message: "密码必须是6-12位(支持数字/字母/下划线/$)",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            登录
          </Button>
          <Button type="primary" htmlType="button" href="#/registered" style={{ marginLeft: '10vh' }}>
            注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Demo;
